<template>
  <Modal
    v-model="showEditPeriodicTaskModal"
    title="编辑定时任务"
    :closable="false"
    :mask-closable="false"
    width="650"
  >
    <Form
      label-position="right"
      :label-width="120"
      ref="periodicTaskForm"
      :model="periodicTaskForm"
      :rules="periodicTaskValidate"
    >
      <FormItem label="名称" prop="name">
        <Input clearable v-model="periodicTaskForm.name" />
      </FormItem>
      <FormItem label="任务(已注册)" prop="task">
        <Select clearable v-model="periodicTaskForm.task" filterable>
          <Option
            v-for="(key, value) in registeredTasks"
            :value="value"
            :label="key"
            :key="value"
          >
          </Option>
        </Select>
      </FormItem>
      <FormItem label="Crontab日程" prop="crontab_id">
        <Select clearable v-model="periodicTaskForm.crontab_id">
          <Option
            v-for="item in crontabSchedules"
            :value="item.id.toString()"
            :key="item.id"
            >{{ item.minute }}&nbsp;&nbsp;{{ item.hour }}&nbsp;&nbsp;{{
              item.day_of_week
            }}&nbsp;&nbsp;{{ item.day_of_month }}&nbsp;&nbsp;{{
              item.month_of_year
            }}&nbsp;&nbsp;(m/h/d/dM/MY)</Option
          >
        </Select>
      </FormItem>
      <FormItem label="一次性任务">
        <RadioGroup v-model="periodicTaskForm.one_off">
          <Radio label="True">是</Radio>
          <Radio label="False">否</Radio>
        </RadioGroup>
      </FormItem>
      <Row>
        <Col span="12">
          <FormItem label="开始时间" prop="start_time">
            <DatePicker
              type="datetime"
              v-model="periodicTaskForm.start_time"
              format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%"
            ></DatePicker>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="过期时间" prop="expires">
            <DatePicker
              type="datetime"
              v-model="periodicTaskForm.expires"
              format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%"
            ></DatePicker>
          </FormItem>
        </Col>
      </Row>
      <FormItem label="启用/停用">
        <RadioGroup v-model="periodicTaskForm.enabled">
          <Radio label="True">启用</Radio>
          <Radio label="False">停用</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="位置参数">
        <Input
          clearable
          v-model="periodicTaskForm.args"
          type="textarea"
          :rows="3"
          placeholder='JSON encoded positional arguments (Example: ["arg1", "arg2", "[arg3, arg4]"])'
        />
      </FormItem>
      <FormItem label="关键字参数">
        <Input
          clearable
          v-model="periodicTaskForm.kwargs"
          type="textarea"
          :rows="3"
          placeholder='JSON encoded keyword arguments (Example: {"key": "value"})'
        />
      </FormItem>
      <FormItem label="描述">
        <Input
          clearable
          v-model="periodicTaskForm.description"
          type="textarea"
          :rows="3"
        />
      </FormItem>
    </Form>
    <div slot="footer">
      <Button type="default" @click="handleEditPeriodicTaskCancel">取消</Button>
      <Button
        type="primary"
        @click="handleCreatePeriodicTaskSubmit('periodicTaskForm')"
        >确定</Button
      >
    </div>
  </Modal>
</template>

<script>
import { updatePeriodicTask } from "@/api/CeleryScheduledTaskService/periodic-task";
import { getRegisteredTasks } from "@/api/CeleryScheduledTaskService/tasks";
import { getCrontabSchedules } from "@/api/CeleryScheduledTaskService/crontab-schedule";

export default {
  name: "periodic-task-edit",
  props: {
    editPeriodicTask: {
      type: Boolean,
      default: false,
    },
    periodicTask: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  watch: {
    editPeriodicTask(val) {
      if (val) {
        this.getRegisteredTasks();
        this.getCrontabSchedules();
      }
    },
    periodicTask(val) {
      if (this.showEditPeriodicTaskModal) {
        this.periodicTaskForm = { ...val };
        this.periodicTaskForm.crontab_id = val.crontab.id.toString();
        this.periodicTaskForm.enabled = val.enabled ? "True" : "False";
        this.periodicTaskForm.one_off = val.one_off ? "True" : "False";
        delete this.periodicTaskForm.crontab;
      }
    },
  },
  computed: {
    showEditPeriodicTaskModal: {
      get() {
        return this.editPeriodicTask;
      },
      set(val) {
        this.$emit("update:editPeriodicTask", val);
        this.$emit("update:periodicTask", {});
      },
    },
  },
  data() {
    return {
      registeredTasks: {},
      crontabSchedules: [],
      periodicTaskForm: {
        id: "",
        name: "",
        task: "",
        enabled: "",
        crontab_id: "",
        start_time: "",
        expires: "",
        one_off: "",
        args: "[]",
        kwargs: "{}",
        description: "",
      },
      periodicTaskValidate: {
        name: [
          { required: true, message: "该字段是必填项。", trigger: "blur" },
        ],
        task: [
          { required: true, message: "该字段是必填项。", trigger: "change" },
        ],
        crontab_id: [
          { required: true, message: "该字段是必填项。", trigger: "change" },
        ],
        start_time: [
          {
            required: true,
            type: "date",
            message: "该字段是必填项。",
            trigger: "change",
          },
        ],
        expires: [
          {
            required: true,
            type: "date",
            message: "该字段是必填项。",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    handleEditPeriodicTaskCancel() {
      this.periodicTaskForm = {
        id: "",
        name: "",
        task: "",
        enabled: "",
        crontab_id: "",
        start_time: "",
        expires: "",
        one_off: "",
        args: "[]",
        kwargs: "{}",
        description: "",
      };
      this.showEditPeriodicTaskModal = false;
      this.$refs["periodicTaskForm"].resetFields();
    },

    handleCreatePeriodicTaskSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          updatePeriodicTask(this.periodicTaskForm)
            .then((res) => {
              if (res.status === 200) {
                this.$Message.info("修改成功");
                this.handleEditPeriodicTaskCancel();
                this.$emit("initPeriodicTaskTable");
              } else {
                this.$Message.error("修改失败");
              }
            })
            .catch((err) => {
              this.$Modal.error({
                title: "系统异常，请联系管理员……",
                content: JSON.stringify(err),
                closable: true,
              });
            });
        }
      });
    },

    getRegisteredTasks() {
      getRegisteredTasks().then((res) => {
        this.registeredTasks = res.data;
      });
    },

    getCrontabSchedules() {
      getCrontabSchedules().then((res) => {
        const data = res.data;
        this.crontabSchedules = data.results;
      });
    },
  },
};
</script>

<style scoped>
</style>
